package com.iqoo.store.dao;

import com.iqoo.store.model.User;
import com.iqoo.store.utils.DataSourceUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.*;

public class UserDao {

    // 使用单例模式获取数据库连接池
    private static ComboPooledDataSource dataSource = DataSourceUtils.getDataSource();

    /**
     * 保存用户到数据库
     *
     * @param user 用户对象
     */
    public void register(User user) {
        Connection conn = null;
        PreparedStatement stmt = null;

        String sql = "INSERT INTO users (username, password, email, phone, role) VALUES (?, ?, ?, ?, ?)";

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getEmail());
            stmt.setString(4, user.getPhone());
            stmt.setInt(5, user.getRole());

            int affectedRows = stmt.executeUpdate();

            if (affectedRows == 0) {
                throw new SQLException("保存用户失败，数据库没有更新任何行。");
            }

            // 获取生成的主键
            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    user.setId(generatedKeys.getInt(1));
                } else {
                    throw new SQLException("保存用户失败，未生成主键。");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 可以添加日志记录或抛出自定义异常
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据用户名查找用户
     *
     * @param username 用户名
     * @return 找到的用户对象，如果未找到则返回 null
     */
    public User login(String username) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        User user = null;

        String sql = "SELECT * FROM users WHERE username = ?";

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setRole(rs.getInt("role"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 可以添加日志记录或抛出自定义异常
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return user;
    }



    /**
     * 更新用户信息
     *
     * @param user 用户对象
     */
    public void update(User user) {
        Connection conn = null;
        PreparedStatement stmt = null;
        String sql = "UPDATE users SET username = ?, password = ?, email = ?, phone = ?, role = ? WHERE id = ?";

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getEmail());
            stmt.setString(4, user.getPhone());
            stmt.setInt(5, user.getRole());
            stmt.setInt(6, user.getId());
            stmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            // 可以添加日志记录或抛出自定义异常
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除用户
     *
     * @param user 用户对象
     */
    public void delete(User user) {
        Connection conn = null;
        PreparedStatement stmt = null;

        String sql = "DELETE FROM users WHERE id = ?";

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, user.getId());

            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            // 可以添加日志记录或抛出自定义异常
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
